# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

"""field.views"""
from __future__ import division, absolute_import
import pyglet
from pyglet import gl
from src import conf, vars
from src import game

#:: Field's view part
def field_init_view(self):
    self.tileset = {} # gfx tiles FIX -> store gfx in res.images
    self.atlas = pyglet.image.atlas.TextureAtlas(width=512, height=512)
    self.batch = pyglet.graphics.Batch()
    # loading tiles
    from src import res
    import os.path
    for file in res.list('tiles/winter/*.png'):
        print 'loaded %s' % file
        img = res.load(file)
        fn = os.path.basename(file)
        id = fn[:fn.rfind('_')] if '_' in fn else os.path.splitext(fn)[0]
        if id not in self.tileset:
            self.tileset[id] = []
        self.tileset[id].append(self.atlas.add(img))
        """
        self.tileset = {
            'l4'   : [0, 1, 2]
            'l4_e' : [0, 1]
        }
        """
    def build_batch(self):
        """Builds batch"""
        ts = vars.tile_size
        vlist, tlist = [], []
        for x, y in self.cloop():
            vlist.extend( # upward
                [x*ts, y*ts] + [(x+1)*ts, y*ts] +
                [(x+1)*ts, (y+1)*ts] + [x*ts, (y+1)*ts]) 
            tex = self.tileset['l%d' % self.zlevel[x][y]][0].get_texture() # XXX view reading from the model
            tc = tex.tex_coords
            uv1 = tc[0:2] # bottom-left
            uv2 = tc[3:5] # bottom-right
            uv3 = tc[6:8] # top-right
            uv4 = tc[9:11] # top-left
            tlist.extend(uv1 + uv2 + uv3 + uv4)
        # todo: change to quad_strip
        self.batch.add(len(vlist)//2, gl.GL_QUADS, None, ('v2i/static', vlist), ('t2f', tlist))
    build_batch(self)

def field_draw(self):
    #from src import game
    #game.export_vars(globals())
    vp = game.vp
    poslist = [(vp.x_shift, vp.y_shift)]
    vp_overflow_x = (vp.x + vp.w) % self.w_px
    vp_overflow_y = (vp.y + vp.h) % self.h_px
    ox = vp.w - vp_overflow_x
    oy = vp.h - vp_overflow_y
    if vp_overflow_x and vp_overflow_y: # C
        poslist += [(ox, oy)]
    if vp_overflow_x:
        poslist += [(ox, vp.y_shift)]
    if vp_overflow_y:
        poslist += [(vp.x_shift, oy)]
        
    #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
    tex = self.tileset['l4'][0].get_texture() # hack, fixme
    gl.glBindTexture(tex.target, tex.id)
    gl.glEnable(gl.GL_TEXTURE_2D)
    for x, y in poslist:
        gl.glPushMatrix()
        gl.glTranslatef(x, y, 0)
        self.batch.draw()
        gl.glPopMatrix()
    gl.glDisable(gl.GL_TEXTURE_2D)
    #glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
